﻿using CRM.Repository.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CRM.Repository.Instance
{
    public class Mysql_Repository<T> : I_Repository<T> where T : class, new()
    {
        private readonly DbContext _dbContext;

        public Mysql_Repository(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void Add(T entity)
        {
            _dbContext.Add<T>(entity);
        }

        public void AddRange(IEnumerable<T> ie)
        {
            _dbContext.AddRange(ie);
        }

        public void Delete(T entity)
        {
            _dbContext.Remove(entity);
        }

        public void DeleteRange(IEnumerable<T> ie)
        {
            _dbContext.RemoveRange(ie);
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<T> QueryAll(Expression<Func<T, bool>>? where = null)
        {
            var iq = (IQueryable<T>)_dbContext.Set<T>();
            if (where != null)
            {
                iq = iq.Where(where);
            }
            return iq;

        }

        public IQueryable<T> QueryAll<type>(bool isAsc, Expression<Func<T, type>> order, Expression<Func<T, bool>>? where = null)
        {
            var iq = this.QueryAll(where);
            return isAsc ? iq.OrderBy(order) : iq.OrderByDescending(order);
        }

        public IQueryable<T> QueryAll<type>(out int total, int skip, int take, bool isAsc, Expression<Func<T, type>> order, Expression<Func<T, bool>>? where = null)
        {
            var iq = this.QueryAll(isAsc, order, where);
            total = iq.Count();
            return iq.Skip(skip).Take(take);

        }

        public int SaveChanges()
        {
            return _dbContext.SaveChanges();
        }

        public void Update(T entity)
        {
            _dbContext.Entry<T>(entity).State = EntityState.Modified;
        }

        public void UpdateRange(IEnumerable<T> ie)
        {
            foreach (var item in ie)
            {
                this.Update(item);
            }
        }
    }
}
